package controller

import (
	"log"
	"net/http"

	"gitee.com/chuanjinge/gopkgserv/api/request"
	"gitee.com/chuanjinge/gopkgserv/api/response"
	"gitee.com/chuanjinge/gopkgserv/internal/service/examsrv"
	"github.com/gin-gonic/gin"
)

// ExamController 提交答案方法
func (ec *ExamController) Submit(c *gin.Context) {
	var req request.ExamSubmitRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("Error binding JSON: %v", err)
		c.JSON(http.StatusBadRequest, response.BaseResponse{Code: 400, Msg: "参数错误"})
		return
	}
	// 从上下文获取 userId
	userIdVal, exists := c.Get("userId")
	if !exists {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "未获取到用户信息"})
		return
	}
	userId, ok := userIdVal.(int64)
	if !ok {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "用户ID类型错误"})
		return
	}
	// 校验 examId 是否属于该 userId
	userExamDao := examsrv.CheckExamBelongsToUser(req.ExamID, userId)
	if userExamDao == nil {
		c.JSON(http.StatusForbidden, response.BaseResponse{Code: 403, Msg: "无权操作该考试"})
		return
	}

	result, err := examsrv.SubmitAnswers(userExamDao, req.Answer)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	c.JSON(http.StatusOK, response.Success(result))
}
